import { Controller, Get, Post, Body, Patch, Param, Delete, Req, Inject, ParseIntPipe, UseGuards, SetMetadata, UnauthorizedException } from '@nestjs/common';
import { UserService } from './user.service';
import { WINSTON_LOGGER_TOKEN } from 'src/log/logger.module';
import { LoginDto } from './dto/login.dto';
import { RegisterDto } from './dto/register.dto';
import { JwtService } from '@nestjs/jwt';
import { LoginGuard } from 'src/common/login.guard';
import { PermissionGuard } from 'src/common/permission.guard';


@Controller('user')
export class UserController {
  // 注入日志
  @Inject(WINSTON_LOGGER_TOKEN)
  private logger;

  constructor(
    private jwtService: JwtService,
    private readonly userService: UserService, 
    @Inject("userList") readonly userList: string[]
  ) {}


  @Get('/getUserId')
  getUserId(@Req() req) {
    const code = this.userService.getUUid();
    req.session.code = code;
    return {
      session: code,
      code: 200
    }
  }

  @Post('checkUser')
  checkUser(@Req() req, @Body() body) {
    // session 验证通过并且用户名和inject注入的匹配
    if(req.session.code === body.sessionInfo && this.userList.includes(body.userName)) {
      return {
        message: `用户 ${body.userName} 校验成功`,
        code: 200
      }
    } else {
      return {
        message: '用户校验失败',
        code: 10001
      }
    }
  }

  // 通过用户id查询用户信息
  @Get('getUserByName/:username')
  @UseGuards(LoginGuard, PermissionGuard)
  @SetMetadata('permission', 'query_aaa')
  async getUserByName(@Param() username: string) {
    const res = await this.userService.findOne(username)
    return {
      code: 200,
      data: res
    }
  }

  // 当登录 access_token 失效是重新刷新获取token 信息
  @Get('refresh/:refreshToken')
  async refresh(@Param() refreshToken: string) {
    try {
      // 验证 refreshToken 是否匹配
      const data = this.jwtService.verify(refreshToken); // 验证
      const user = await this.userService.findUserById(data.id);

      const access_token = this.jwtService.sign({
        id: user.id,
        username: user.username,
      }, {
        expiresIn: '30m'
      });

      const refresh_token = this.jwtService.sign({
        id: user.id
      }, {
        expiresIn: '7d'
      });

      return {
        access_token,
        refresh_token
      }
    } catch(e) {
      throw new UnauthorizedException('token 已失效，请重新登录');
    }
  }


  // 用户登录
  @Post('login')
  async login(@Body() user: LoginDto) {
    const foundUser = await this.userService.login(user);
    if(!foundUser) {
      return {
        code: 401,
        data: '登陆失败'
      }
    }

    // access_token 
    const access_token = await this.jwtService.signAsync({
      id: foundUser.id,
      username: foundUser.username
    }, {
      expiresIn: '30m'
    })

     // refresh_token  
     const refresh_token = await this.jwtService.signAsync({
      id: foundUser.id,
    }, {
      expiresIn: '7d'
    })

    return {
      code: 200,
      data: foundUser,
      access_token,
      refresh_token
    };
  }

  // 注册新用户
  @Post('register')
  async register(@Body() user: RegisterDto) {
    const res = await this.userService.register(user);
    if(res) {
      return {
        code: 200,
        data: '注册成功'
      }
    }
  }

  // 初始化用户数据及关联关系
  @Get('init')
  async initData() {
    await this.userService.initData();
    return {
      code: 200,
      data: '数据初始化成功'
    }
  }
}
